import { _decorator, Component, instantiate, Size, tween, UITransform, Node, Vec3 } from 'cc';
import { CocosUtils } from '../../../Framework/Scripts/Utils/CocosUtils';
const { ccclass, property } = _decorator;

@ccclass('BgAni')
export class BgAni extends Component {

    time: 6;
    height: number;

    start() {
        //下面的
        let bg1:Node = this.node.children[0];
        //上面的那张   
        let bg2 = this.node.children[1];

        this.createBg(bg1);
        this.createBg(bg2);
        this.playAni();
    }

    createBg(parent:Node){
        const canvasSize: Size = CocosUtils.winSize();
        // console.log('Canvas size:', canvasSize);
        let itemSize = new Size(120,120);
        let offsetX = 210;
        let offsetY = 240;

        let heightCount = Math.ceil(canvasSize.height/offsetY);
        let widthCount = Math.ceil(canvasSize.width/offsetX);
        // console.log('=======heightCount======')
        let startX = -canvasSize.width/2 + itemSize.width/2;  
        let startY = canvasSize.height/2 - itemSize.height/2;

        let pre = this.node.getChildByName('spQiu');

        for (let i = 0; i < widthCount; i++) {
            let offset = 0;
            if(i % 2 !== 0){
                offset = 120;
            }
            for(let j = 0; j < heightCount; j++){
                let item:any = instantiate(pre);
                item.active = true;
                item.parent = parent;
                let xx = startX + offsetX*i;
                let yy = startY - offsetY*j - offset;
                item.setPosition(xx,yy,0);
            }
        }
    }

    playAni() {
        //创建背景滚动的球
        const canvasSize: Size = CocosUtils.winSize();
        // console.log('Canvas size:', canvasSize);
        let time = 6;

        //下面的
        let bg1 = this.node.children[0];
        let h = bg1.getComponent(UITransform).height;
        tween(bg1)
            .to(time, { position: new Vec3(0, -h, 0) })
            .to(0, { position: new Vec3(0, h, 0) })
            .to(time, { position: new Vec3(0, 0, 0) })
            .union()
            .repeatForever()
            .start()

        //上面的那张   
        let bg2 = this.node.children[1];
        tween(bg2)
            .to(time * 2, { position: new Vec3(0, -h, 0) })
            .to(0, { position: new Vec3(0, h, 0) })
            .union()
            .repeatForever()
            .start();
    }
}


